class Tag < ActiveRecord::Base
  has_and_belongs_to_many :articles, :order => 'published_at DESC'
  
  validates_uniqueness_of :name, :display_name
  
  def self.get(name)
    tagname = name.tr(' ', '').downcase
    name = tagname.capitalize
    tag = find_by_name_or_display_name(tagname, name)
    
    if tag.nil?
      tag = Tag.create(:name => tagname, :display_name => name)
    end
    
    tag
  end
  
  def self.find_by_name_or_display_name(tagname, name)
    Tag.find(:first, :conditions => [%{name = ? OR display_name = ? OR display_name = ?}, tagname, tagname, name])
  end
  
  def to_s
    display_name
  end
end